package com.ec.project.service.impl;

import com.ec.project.model.entity.AskMsg;
import com.ec.project.service.FeiShuService;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.*;

/**
 * @author EnergyCore01
 * @date 2024/12/28 15:36
 */
@Service
@Slf4j
public class FeiShuServiceImpl implements FeiShuService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void hanldeMsg(P2MessageReceiveV1 event) throws Exception {
        P2MessageReceiveV1Data event1 = event.getEvent();
        EventSender sender = event1.getSender();
        String openId = sender.getSenderId().getOpenId();

        String content = event1.getMessage().getContent();
        AskMsg askMsg = new AskMsg();
        askMsg.setAskId(openId);
        askMsg.setContent(content);

        log.info("=====================================");
        log.info(Jsons.DEFAULT.toJson(event));
        log.info("=====================================");
        System.out.println(event.getRequestId());
        //sendMsg(event);
        rabbitTemplate.convertAndSend("BotDirectExchange", "ASK", askMsg);
    }

    @Override
    public void sendMsg(P2MessageReceiveV1 event) throws Exception {

        P2MessageReceiveV1Data event1 = event.getEvent();
        EventSender sender = event1.getSender();
        String openId = sender.getSenderId().getOpenId();

        String content = event1.getMessage().getContent();

        // 构建client
        Client client = Client.newBuilder("cli_a7cf6aa03471500c",
                "10pkQQwkvRenB2Z7Od4ErcIJueOXy6sk").build();

        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("open_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId(openId)
                        .msgType("text")
                        .content(content)
                        .uuid("")
                        .build())
                .build();

        // 发起请求
        CreateMessageResp resp = client.im().message().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(),
                    Jsons.createGSON(true, false)
                            .toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody())))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }
}
